<?php

namespace plugin\webman\foursport;
use support\Db;
use GatewayWorker\Lib\Gateway;
use support\Redis;
use plugin\webman\common\Common;
use plugin\webman\foursport\Method3;


class Sports
{

    // 定时器发送状态
    public static function timer()
    { 

        $time = 60-date('s',time());
        $data=[
            'code'=>1,
            'msg'=>'本局剩余时间',
            'info'=>(int)$time
        ];
        Gateway::sendToAll(Common::returndata('timer',$data));

        switch ($time) {
            case '60':
                $data=[
                    'code'=>1,
                    'msg'=>'35秒后开始比赛',
                    'info'=>[]
                ];
                Gateway::sendToAll(Common::returndata('game_start1',$data));
                break;
            case '59':
                // 更新投注总额和个人投注信息
                $expect=Common::getexpect();
                $data=[
                    'code'=>1,
                    'msg'=>'赛道投注金额更新',
                    'info'=>Method3::getsaidao($expect),
                ];
                Gateway::sendToAll(Common::returndata('upsaidao',$data));
                break;       
            case '55':
                self::robotbet();
                break;
            case '45':
                self::robotbet();
                break;
            case '40':
                self::robotbet();
                break;
            case '35':
                self::robotbet();
                break;
            case '30':
                self::robotbet();
                break;
            case '25':
                // 此时发送谁是冠亚军
                $paiming = Method3::getmingci();
                
                // 走分润逻辑
                self::fenrun($paiming);
                $info['list']=$paiming;
                $info['expect']=Common::getexpect();
              
                $data=[
                    'code'=>1,
                    'msg'=>'准备开始倒计时5秒',
                    'info'=>$info
                ];
                Gateway::sendToAll(Common::returndata('game_start',$data));
                break;    
            


        }
       
    }  

    public  static function getuserinfo($client_id,$data){
        $info = Common::getuserinfo($data['uid']);
        $touzhu = Db::table("wa_sports_touzhu")->where(["expect"=>$data['expect'],'uid'=>$data['uid']])->get()->map(function ($value) {return (array)$value;})
        ->toArray();
        if(!$touzhu){
            $info['result']='未参与本期投注';
        }else{

            if($touzhu[0]['ifwin']==1){
                $info['result']='恭喜中奖，投注'.$touzhu[0]['coin'].',获得'.$touzhu[0]['reward'];
            }else{
                $info['result']='失败，损失'.$touzhu[0]['coin'];
            }

            
        }
        //   获取运动员近100期冠军次数
        $tongji = Method3::get_npc_win_num();
        $info['tongji']=$tongji;

        $data=[
            'code'=>1,
            'msg'=>'最新用户余额信息',
            'info'=>$info
        ];
        return $data;
        // Gateway::sendToAll(Common::returndata('returnuserinfo',$data));
    }

    // 获取开奖结果
    public static function getresult($client_id,$data){
        $list = Db::table("wa_sports_touzhu")->where(['uid'=>$data['uid'],"expect"=>$data['expect']])->get()->map(function ($value) {return (array)$value;})
        ->toArray();
        // var_dump($list);die;
        if($list){
            $sum = Db::table("wa_sports_touzhu")->where(['uid'=>$data['uid'],"expect"=>$data['expect']])->sum("reward");
            $sum2 = Db::table("wa_sports_touzhu")->where(['uid'=>$data['uid'],"expect"=>$data['expect'],'ifwin'=>1])->sum("coin");
            $sum3 =$sum + $sum2;
            $result = "本次投注获得".$sum3.'宝石';
        }else{
            $result = "未参与投注";
        }
        $data=[
            'code'=>1,
            'msg'=>'获取成功',
            'info'=>$result
        ];
        return $data;
    }

    // 名次传过来
    public static function fenrun($paiming){
    // public static function fenrun(){     //测试打开
    //     $paiming = Method3::getmingci();  //测试打开
        // 找出冠军
        foreach($paiming as $kt => $vt){
            if($vt['mingci']==1){
                $gj['id'] = $vt['id'];
                $gj['name']=$vt['name'];
                $gj['mingci']=$vt['mingci'];
                $new[]=$gj;
            }
        }

        $guanjun = $new[0];
        
        $expect = Common::getexpect();
        // $expect = '202401310827';    //测试打开
        // $guanjun = [
        //     'id'=>2,
        //     'name'=>'红发猿',
        //     'mingci'=>1
        // ];
        // $tzlist = Db::table("wa_sports_touzhu")->where(['expect'=>$expect,'is_robot'=>0])->get()->map(function ($value) {return (array)$value;})
        // ->toArray();
     
        $tzlist = Db::table("wa_sports_touzhu")->where(['expect'=>$expect])->get()->map(function ($value) {return (array)$value;})
        ->toArray();
        
        foreach($tzlist as $k=>$v){

            if($v['type']==1){
                // 猜谁是冠军
                if($v['npcid']==$guanjun['id']){
                    // 中奖
                    // 计算获取宝石   按照投入金额 1：0.9的赔率
                    // $jiangjin = $v['coin']*0.9;
                    // $reward = $jiangjin + $v['coin']; //赢得+投注一起返还

                    // 其他赛道输得总数，，除去抽水，，除于赢得赛道总额，，然后按比例分配   

                    $rules = Db::table("wa_foursport_rule")->where(['id'=>1])->first();
                    $bili = $rules->bili;
                    
                    //冠军赛道总投注
                    $all_guanjun = Db::table("wa_sports_touzhu")->where(['expect'=>$expect,'type'=>1,'npcid'=>$guanjun['id']])->sum('coin');
                    
                    // 总投注
                    $all = Db::table("wa_sports_touzhu")->where(['expect'=>$expect,'type'=>1])->sum('coin');
                    // var_dump($all_guanjun,$all);die;
                    // 其他赛道投注进
                    $all_ohter = $all - $all_guanjun;
                    // 剪掉抽水 剩余金额
                    $left =$all_ohter - $all_ohter*$bili*0.01;
                    $guafenbili = round($left / $all_guanjun,2);
                    $jiangjin = $v['coin'] * $guafenbili;
                    $reward = $jiangjin + $v['coin'];
                    // var_dump($v['id']);
                    var_dump('冠军赛道'.$all_guanjun,"总投入".$all,"其他赛道".$left,"奖金".$jiangjin,"投入+奖金".$reward);
                    Method3::zhongjiang($v['id'],$guanjun,1,$jiangjin);
                    Common::updateusercoin($v['uid'],$reward,1);

                    Db::table("wa_usercoin_record")->insert([
                        'uid'=>$v['uid'],
                        'coin'=> $v['coin']*0.9,
                        'type'=>1,
                        'remark'=>'猜对冠军'.$guanjun['name'],
                        'addtime'=>date("Y-m-d H:i:s")
                    ]);
                }else{
                    Method3::zhongjiang($v['id'],$guanjun,0);
                }
            }
            if($v['type']==2){
                //猜谁不是冠军
                if($v['npcid']!=$guanjun['id']){
                    // 中奖
                    $jiangjin = $v['coin']*0.9;
                    $reward = $jiangjin + $v['coin']; //赢得+投注一起返还
                    Method3::zhongjiang($v['id'],$guanjun,1,$jiangjin);
                    Common::updateusercoin($v['uid'],$reward,1);

                    Db::table("wa_usercoin_record")->insert([
                        'uid'=>$v['uid'],
                        'coin'=> $v['coin']*0.9,
                        'type'=>1,
                        'remark'=>'猜对不是冠军'.$guanjun['name'],
                        'addtime'=>date("Y-m-d H:i:s")
                    ]);
                }else{
                    Method3::zhongjiang($v['id'],$guanjun,0);
                }
            }
        }
    }

    
    // 检查url
    public static function checkurl($client_id,$data){
        $datas = explode('&',$data['data']['data']);
        foreach($datas as $k =>$v){
            $chai = explode('=',$v);
            
            $a[0]=$chai[0];
            $a[1]=$chai[1];
            $new[]=$a;
        }
        // var_dump($new);die;
        foreach($new as $kt =>$vt){
            $b[$vt[0]]=$vt[1];
            $new2=$b;  //所有前端给的参数都在这里接受.  传的啥可以直接取出来
        }

        $checktoken =   Common::checktoken2($client_id,$new2['uid'],$new2['token']);
        if($checktoken!=1){
            Gateway::sendToClient($client_id,Common::returndata('tokenexpire',$data));
            exit();
        }
        $user['userinfo']['token'] = Common::updatetoken2($new2['uid']);
        $user['userinfo'] = Common::getuserinfobyid($new2['uid']); 
        $rs['code']=1;
        $rs['msg']='登录成功';
        $rs['info']=$user;
        return $rs;
    }
    // 进入房间
    public static function enterroom($client_id,$data){
        $checktoken =   Common::checktoken($client_id,$data['uid'],$data['token']);
        if($checktoken==1){
            $expect = Common::getexpect();
            //   获取运动员近100期冠军次数
            $tongji = Method3::get_npc_win_num();
            // 当前用户信息
          
            $userinfo = Common::getuserinfobyid($data['uid']);
            $info['expect']=$expect;
            $info['userinfo']=$userinfo;
            $info['tongji']=$tongji;
            $info['mingci']=Method3::getmingci_expect();
            $peizhi = Db::table("wa_foursport_rule")->where("id",1)->first();
            // var_dump($peizhi);die;
            $info['noguanjunstatus'] = $peizhi->noguanjun;

            // 获取个人投注金额 和 每个赛道的投注金额
            $info['betinfo']=Method3::getbetinfo($data['uid'],$expect);
            // var_dump($info['mingci']);
            $data=[
                'code'=>1,
                'msg'=>'进入成功',
                'info'=>$info
            ];
            return $data;
        }
    }


// 机器人投注
static function robotbet(){
    $rule = Db::table("wa_foursport_rule")->where("id",1)->first();
    $start = $rule->starttime;
    $end = $rule->endtime;
    $max = $rule->max;
    $min = $rule->min;
    $starttime = strtotime(date("Y/m/d"." ".$start));
    $endtime = strtotime(date("Y/m/d"." ".$end));
    if(time()>=$starttime && time()<=$endtime){
        $array = Db::table('wa_users')->where("isrobot",1)->get()->map(function ($value) {return (array)$value;})
        ->toArray();
        // $numToPick = rand(1, count($array)); // 需要抽取的随机数量
        $numToPick = $rule->robotamount; // 需要抽取的随机数量
        // $numToPick = 1; 
        $expect = Common::getexpect();
        if($numToPick>0){
            // 创建一个空数组存放抽取到的元素
            $pickedElements = [];
            for ($i = 0; $i < $numToPick; $i++) {
                $index = array_rand($array); // 生成随机索引值
                $element = $array[$index]; // 根据索引值获取元素
                
                unset($array[$index]); // 将已经选取的元素移除原始数组，确保不会重复选取相同的元素
                
                $pickedElements[] = $element; // 添加到结果数组中
            }

            foreach ($pickedElements as $k => $v) {
                $randnpc = rand(1,4);
                $npcname = Method3::getnpcname($randnpc);
        
                $record = [
                    'uid'=>$v['id'],
                    'npcid'=>$randnpc,
                    'npcname'=>$npcname,
                    'coin'=>rand($min,$max),
                    'expect'=>$expect,
                    "is_robot"=>1,
                    'ifwin'=>2,
                    'reward'=>'0.00',
                    'addtime'=>time(),
                    'type'=>1
                ];
                $id = Db::table('wa_sports_touzhu')->insert($record);
                            // 发送广告赛道投注金额更新
                $data=[
                    'code'=>1,
                    'msg'=>'赛道投注金额更新',
                    'info'=>Method3::getsaidao($expect),
                ];
                Gateway::sendToAll(Common::returndata('upsaidao',$data));
            }
        }
       
        
    }else{
        var_dump("不再机器人投注时间内");
    }

   
}


    //   投注
  static function touzhu($client_id,$data){
        $checktoken =   Common::checktoken($client_id,$data['uid'],$data['token']);
        if($checktoken==1){
            $time = 60-date('s',time());
            if($time<25){
                $data=[
                    'code'=>1058,
                    'msg'=>'封盘中，禁止投注',
                    'info'=>[]
                ];
                return $data; 
            }
            $expect = Common::getexpect();
             // 金币是否足够
             $usercoin = Common::getusercoin($data['uid']);
             if($usercoin<$data['coin']){
                 $data=[
                     'code'=>1056,
                     'msg'=>'金币不足',
                     'info'=>[]
                 ];
                 return $data;
             }
             $npcname = Method3::getnpcname($data['npcid']);
             
             $ifexit=Db::table("wa_sports_touzhu")->where(["uid"=>$data['uid'],"expect"=>$expect,"npcid"=>$data['npcid']])->get()->map(function ($value) {return (array)$value;})
             ->toArray();
             if($ifexit){
                $newcoin = $ifexit[0]['coin']+$data['coin'];
                Db::table("wa_sports_touzhu")->where(["uid"=>$data['uid'],"expect"=>$expect,"npcid"=>$data['npcid']])->update(['coin'=>$newcoin]);
             }else{
                $record = [
                    'uid'=>$data['uid'],
                    'npcid'=>$data['npcid'],
                    'npcname'=>$npcname,
                    'coin'=>$data['coin'],
                    'expect'=>$expect,
                    "is_robot"=>0,
                    'ifwin'=>2,
                    'reward'=>'0.00',
                    'addtime'=>time(),
                    'type'=>$data['type']
                ];
                $id = Db::table('wa_sports_touzhu')->insert($record);
             }
             
               // 扣除金币
            Common::updateusercoin($data['uid'],$data['coin'],0);
            $info['userinfo']=Common::getuserinfobyid($data['uid']);
            $info['allbet']=Db::table("wa_sports_touzhu")->where("uid",$data['uid'])->where("expect",$expect)->sum("coin");
            $info['betinfo']=Method3::getbetinfo($data['uid'],$expect);

            // 发送广告赛道投注金额更新
            $data=[
                'code'=>1,
                'msg'=>'赛道投注金额更新',
                'info'=>Method3::getsaidao($expect),
            ];
            Gateway::sendToAll(Common::returndata('upsaidao',$data));

            $data = [
                'code'=>1,
                'msg'=>'投注成功',
                'info'=>$info
            ];
            return $data;
        }
  }

  public static function myrecord($client_id,$data){
    $list = Db::table('wa_sports_touzhu')->where("uid",$data['uid'])->orderByDesc('id',true)->get()->map(function ($value) {return (array)$value;})
    ->toArray();
    foreach($list as $kt =>$vt){
        if($vt['result']==NULL){
            $vt['result']=0;
            $vt['result_name']="";
        }
    }
    $info['tzlist']=$list;
    // 近10期的排名
    $expect =   Common::getexpect();
    for($i=0;$i<10;$i++){
        $expect = $expect-1;
        $new[$i]['expect']=$expect;
        $new[$i]['list2'] = self::getmingcibyexpect($expect);
        // $new[$i]['list2'] = Db::table("wa_sports_paiming")->where("expect", $expect)->get()->map(function ($value) {return (array)$value;}) ->toArray();
    }
    // 共投入 共产出
    $info['bet']['all']=(string)Db::table("wa_sports_touzhu")->where("uid",$data['uid'])->sum("coin");
    $info['bet']['reward']=(string)Db::table("wa_sports_touzhu")->where("uid",$data['uid'])->sum("reward");
    // foreach($new as $k=>$v){
   
    //     $list1 = Db::table("wa_sports_paiming")->where("expect",$v)->get()->map(function ($value) {return (array)$value;})
    //     ->toArray();
    //     // var_dump($list);die;
    //     $new2[]=$list1;
    //     // $new2[]=$v;
    // }
    // // // $info['rank'] = Db::table('wa_sports_paiming')->where
    $info['list']=$new;
    $data = [
        'code'=>1,
        'msg'=>'获取成功',
        'info'=>$info
    ];
    return $data;
  }

  public static function getmingcibyexpect($expect){
    $npcinfo = Method3::npcinfo();
    foreach ($npcinfo as $key => $value) {
        $mingci=Db::table("wa_sports_paiming")->where(['npcid'=>$value['id'],'expect'=>$expect])->get()->map(function ($value) {return (array)$value;})->toArray();
        if($mingci){
            $value['mingci']=$mingci[0]['mingci'];
        }else{
            $value['mingci']=0;
        }
        

        $new[]=$value;
    }
    return $new;
  }

    


}